-------------------------------------------------
-- 成神之路-英雄成长(神将辅助)

-- db.heroGrowTask[id]
-------------------------------------------------
local Util = require("common.Util")
local MailExcel = require("excel.mail")
local HeroExcel = require("excel.hero").hero
local PresentExcel = require("excel.present")
local OpenActExcel = require("excel.openAct")
local Msg = require("core.Msg")
local ObjHuman = require("core.ObjHuman")
local Grid = require("bag.Grid")
local MailManager = require("mail.MailManager")

HEROGROW_OPENTIME = 7 * 86400

-- 
local function getActLeftTime(human)
    local diffTime = os.time() - human.db.createTime
    if diffTime < HEROGROW_OPENTIME then
        return HEROGROW_OPENTIME - diffTime
    end
    return 0
end

function isOpen(human)
    if true then
        return
    end

    -- 创角七天
    if getActLeftTime(human) > 0 then
        return true
    end
end

local function getCurCnt(human, id)
    if not human.db.heroGrowTask then
        return 0
    end
    return human.db.heroGrowTask[id] or 0
end

--  填充活动任务数据
function makeTaskData(net, config, id, human)   
    net.id = id
    net.desc = config.desc 
    net.cur  = getCurCnt(human, id)
    net.max = config.taskCnt    
    net.reward[0] = #config.reward
    for i = 1, net.reward[0] do
		local itemID = config.reward[i][1]
        local itemCnt = config.reward[i][2]
        Grid.makeItem(net.reward[i], itemID, itemCnt)
    end    
end

function query(human)
    local msgRet = Msg.gc.GC_PRESENT_HERO_GROW_QUERY 
    msgRet.leftTime = getActLeftTime(human)
    msgRet.list[0] = #OpenActExcel.heroGrow 
    for id, config in ipairs(OpenActExcel.heroGrow) do     
        makeTaskData(msgRet.list[id], config, id, human)  
    end    
    --Msg.trace(msgRet)
    Msg.send(msgRet, human.fd)
end

local function addOpenServerHeroCnt(human, id)
    local tableConfig = OpenActExcel.heroGrow[id]
    if not tableConfig then return end

    -- 已经达到完成上限
    if getCurCnt(human, id) >= tableConfig.taskCnt then
        return
    end 

    human.db.heroGrowTask = human.db.heroGrowTask or {}
    human.db.heroGrowTask[id] = (human.db.heroGrowTask[id] or 0) + 1
    
    -- 存db
    ObjHuman.save(human)

    --完成一次 发放奖励一次   
    local title = MailExcel.mail[71].title
    local content = Util.format(MailExcel.mail[71].content, tableConfig.special)
    local senderName = MailExcel.mail[71].senderName    
    MailManager.add(MailManager.SYSTEM, human.db._id, title, content, tableConfig.reward, senderName)
end

-- 回调
function addOpenServerHeroCntEx(human, star, heroID) 
	if not isOpen(human) then return end
   
    star = star or 0
    for id, tableData in ipairs(OpenActExcel.heroGrow) do   
        if tableData and star == tableData.special then
            addOpenServerHeroCnt(human, id, heroID)
        end
    end
end

